#pragma once

#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

static const std::string default_dict = "./dictionary.txt";
static const std::string sep = ": ";

class Dict
{
public:
    Dict(const std::string& path = default_dict)
        : _path(path)
    {
    }
    bool LoadDict()
    {
        std::ifstream in(_path);
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open " << _path << " error!";
            return false;
        }

        std::string line;
        while (std::getline(in, line))
        {
            int pos = line.find(sep);
            if (pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "解析: " << line << " 失败";
                continue;
            }
            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());
            if (english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING) << "解析: " << line << " 失败";
                continue;
            }

            _dict.emplace(english, chinese);
        }

        in.close();
        return true;
    }

    std::string Translate(const std::string& word, const InetAddr& client)
    {
        auto it = _dict.find(word);
        if(it == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入翻译模块,[" << client.Ip() << " : " << client.Port() << "]# " << word << " -> None";
            return "None";
        }

        LOG(LogLevel::DEBUG) << "进入翻译模块,[" << client.Ip() << " : " << client.Port() << "]# " << word << " -> "<< it->second;
        return it->second;
    }

private:
    std::string _path; // 路径+文件名
    std::unordered_map<std::string, std::string> _dict;
};